﻿using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;

namespace Perceptron.Engine
{
    public static class BitmapExtensions
    {
        public static T[,] Binarize<T>(this Bitmap bitmap, T zeroValue, T oneValue)
        {
            using (var viewableBitmap = new LockedBitmap(bitmap, ImageLockMode.ReadWrite))
            {
                var bytesCount = Math.Abs(viewableBitmap.BitmapData.Stride) * viewableBitmap.Bitmap.Height;
                var bytes = new byte[bytesCount];

                Marshal.Copy(viewableBitmap.BitmapData.Scan0, bytes, 0, bytes.Length);

                var bytesPerPixel = LockedBitmap.BytesPerPixel;
                var height = viewableBitmap.Bitmap.Height;
                var width = viewableBitmap.Bitmap.Width;
                var strideLength = viewableBitmap.BitmapData.Stride;
                var arr = new T[bitmap.Width, bitmap.Height];
                for (int y = 0; y < height; ++y)
                {
                    var currentRow = y * strideLength;
                    for (int x = 0, xPointer = 0; x < width; ++x, xPointer += bytesPerPixel)
                    {
                        arr[x, y] = bytes[currentRow + xPointer] > 128 ? oneValue : zeroValue;
                    }
                }

                return arr;
            }
        }

        public static Rectangle GetFullSizeRectangle(this Bitmap bitmap)
        {
            return new Rectangle
            {
                Height = bitmap.Height,
                Width = bitmap.Width
            };
        }

    }
}
